from PySide6.QtGui import *
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from common_code import *
import re

# 定义第一个页面
class Page_21MM(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("21MM 集约文检查工具")
        self.label.setAlignment(Qt.AlignCenter)  # 方法1：直接设置对齐方式
        self.Jira_path = OpenFileWidget('Jira path:    ')
        self.Module_path = OpenFileWidget('Module path:    ')
        self.CheckList_path = OpenFileWidget('CheckList path:    ')
        self.start_btn = StartButtonWidget(self.start_exce)
        self.table_window = TableWindow(self)
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.Jira_path)
        layout.addWidget(self.Module_path)
        layout.addWidget(self.CheckList_path)
        layout.addWidget(self.start_btn)
        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        layout.addWidget(separator)
        layout.addWidget(self.table_window)
        self.setLayout(layout)

    def clear(self):
        # 清除UI中的输入和显示
        self.Jira_path.clear()
        self.Module_path.clear()
        self.CheckList_path.clear()
        self.start_btn.clear()
        self.table_window.clear_table()
    
    def start_exce(self):
        try:
            jira_reader = ExcelReader(self.Jira_path.file_name)
            # 读取整个文件的数据
            jira_data = jira_reader.read_all_data()
            # print("整个文件的数据:", jira_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取Jira文件失败: {e}")
            return
        try:
            module_reader = ExcelReader(self.Module_path.file_name)
            # 读取整个文件的数据
            module_data = module_reader.read_all_data()
            # print("整个文件的数据:", module_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取Module文件失败: {e}")
            return
        try:
            CheckList_reader = ExcelReader(self.CheckList_path.file_name)
            # 读取整个文件的数据
            CheckList_data = CheckList_reader.read_all_data()
            # print("整个文件的数据:", CheckList_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取CheckList文件失败: {e}")
            return

        sample_data = []
        check_dict = {
            "キー":"Jira",
            "要約":"織り込み内容（日文）",
            "仕向け":"仕向地",
            "解析結果":"発生要因",
            "対策内容":"対策",
            "背反の検討結果":"变更影响范围识别",
            "要因区分":"要因区分（障害）",
            "検出すべき工程":"検出すべき工程（障害）",
            "混入工程":"混入工程（障害）",
            "修正規模":"修正规模"
        }

        try:
            jira_dict = {}
            jira_columns = {}
            jira_col_list = ["キー","要約","仕向け","解析結果","対策内容","背反の検討結果","要因区分","検出すべき工程","混入工程","修正規模"]
            for key,values in jira_data.items():
                for i,value in enumerate(values):
                    tmp_dict = {}
                    if i == 3:
                        for k,val in enumerate(value):
                            for col_list in jira_col_list:
                                if str(val).strip() == col_list:
                                    jira_columns[col_list] = k
                        
                    if i >= 4:
                        for name,column in jira_columns.items():
                            tmp_dict[check_dict[name]] = str(value[column]).strip()
                        jira_dict[tmp_dict["Jira"]] = tmp_dict
            
            match = re.search(r'(\d{2})(\d{2})(\d{2})([A-Z]{1}).xlsx$', self.Module_path.file_name)
            if not match:
                QMessageBox.critical(self, "错误", f"文件{self.Module_path.file_name}格式不正确，缺少'XXYYZZF'形式版本号。")
                return
            part1, part2, part3, suffix = match.groups()
            # 组合各部分并插入点号
            sheet_str = f"{part1}.{part2}.{part3}.{suffix}"
            module_no = []
            module_column = 0
            Trunk_column = 0
            Design_column = 0
            o_list = ["PD","CT","IT","PD Rv\nResult","MK Rv\nResult","CT Rv\nResult","IT Rv\nResult"]
            o_column = []
            module_columns = {}
            for key,values in module_data.items():
                if sheet_str in key:
                    for i,val in enumerate(values):
                        if i == 3:
                            for v, va in enumerate(val):
                                va_tmp = str(va).strip()
                                if va_tmp == "开发评价":
                                    module_column = v
                                    break
                                for o in o_list:
                                    if va_tmp == o:
                                        o_column.append(v)
                                if va_tmp == "影响机种判断\n(Trunk)":
                                    Trunk_column = v
                                if va_tmp == "涉及到Design变更":
                                    Design_column = v
                                for ch,di in check_dict.items():
                                    if va_tmp == di:
                                        module_columns[di] = v
                            
                            if module_column == 0:
                                QMessageBox.critical(self, "错误", f"Module文件, 第四行没有找到[开发评价]列。")
                                return
                            if Trunk_column == 0:
                                QMessageBox.critical(self, "错误", f"Module文件, 第四行没有找到[影响机种判断\n(Trunk)]列。")
                                return
                            if Design_column == 0:
                                QMessageBox.critical(self, "错误", f"Module文件, 第四行没有找到[涉及到Design变更]列。")
                                return
                            if len(module_columns) != len(check_dict):
                                QMessageBox.critical(self, "错误", f"Module文件, 第四行[Jira]数据对应列数据不全。")
                                return
                            
                        if i >= 4 and val[0] is not None:
                            module_no.append(str(val[0]).strip())
                            for col in o_column:
                                if str(val[col]).strip() != "○":
                                    sample_data.append(["Module文件", f"[{key}][{get_column_letter(col+1)}{i+1}]","单元格数据不是[○]"])
                            for v, va in enumerate(val):
                                if v < module_column and va is None:
                                    sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{i+1}]","单元格为[None]"])
                                
                            if str(val[Trunk_column]).strip() == "○":
                                if (str(val[Design_column]).strip() != "○" 
                                    or (str(val[Design_column+1]).strip() == "None" or str(val[Design_column+1]).strip() == "-")
                                    or (str(val[Design_column+2]).strip() == "None" or str(val[Design_column+2]).strip() == "-")
                                    or (str(val[Design_column+3]).strip() == "None" or str(val[Design_column+3]).strip() == "-")
                                    or (str(val[Design_column+4]).strip() == "None" or str(val[Design_column+4]).strip() == "-")
                                    or (str(val[Design_column+5]).strip() == "None" or str(val[Design_column+5]).strip() == "-")):
                                    sample_data.append(["Module文件", f"[{key}][{get_column_letter(Design_column)}{i+1}-{get_column_letter(Design_column+5)}{i+1}]","单元格涉及到Design变更数据有[None/-],检查失败"])
                            if str(val[column_index_from_string("AM")-1]).strip() != "OK":
                                sample_data.append(["Module文件", f"[{key}][AM{i+1}]","单元格[确认结果]数据结果不是[OK]"])
                            if str(val[column_index_from_string("AV")-1]).strip() != "OK" and str(val[column_index_from_string("AV")-1]).strip() != "-":
                                sample_data.append(["Module文件", f"[{key}][AV{i+1}]","单元格[确认结果]数据结果不是[OK/-]"])
                            if str(val[column_index_from_string("BB")-1]).strip() != "OK":
                                sample_data.append(["Module文件", f"[{key}][BB{i+1}]","单元格[确认结果]数据结果不是[OK]"])
                            
                            jira_cell = str(val[module_columns["Jira"]]).strip()
                            if jira_cell in jira_dict:
                                for module,column in module_columns.items():
                                    if jira_dict[jira_cell][module] != str(val[column]).strip():
                                        sample_data.append(["Module文件", f"[{key}][{get_column_letter(column+1)}{i+1}]",f"单元格[{jira_cell}:{module}]数据与Jira文件数据不一致"])
                            else:
                                if "PROBL" in jira_cell:
                                    sample_data.append(["Module文件", f"[{key}][{get_column_letter(module_columns["Jira"])}{i+1}]",f"单元格[Jira:{jira_cell}]数据在Jira文件中未找到对应数据"])
                            
            if "表紙" in CheckList_data:
                tmp_data = CheckList_data["表紙"]
                pattern = r'(\d{4}/\d{1,2}/\d{1,2})$'
                matches = re.search(pattern, tmp_data[38][column_index_from_string("J")-1])
                if matches:
                    J_date = str(matches.group(1)).strip()
                else:
                    J_date = None
                matches = re.search(pattern, tmp_data[38][column_index_from_string("O")-1])
                if matches:
                    O_date = str(matches.group(1)).strip()
                else:
                    O_date = None
                matches = re.search(pattern, tmp_data[38][column_index_from_string("T")-1])
                if matches:
                    T_date = str(matches.group(1)).strip()
                else:
                    T_date = None
                if J_date is not None and O_date is not None and T_date is not None:
                    if J_date == O_date == T_date:
                        if is_valid_date(J_date) == False:
                            sample_data.append(["CheckList文件", "[表紙][J39-O39-T39]","单元格中日期是无效日期"])
                    else:
                        sample_data.append(["CheckList文件", "[表紙][J39-O39-T39]","单元格中日期数据不一致"])
                else:
                    sample_data.append(["CheckList文件", "[表紙][J39-O39-T39]", "部分日期数据缺失或错误"])
            else:
                sample_data.append(["CheckList文件", "", "未找到[表紙]sheet页"])

            if "変更履歴" in CheckList_data:
                tmp_data = CheckList_data["変更履歴"]
                for i,val in enumerate(tmp_data):
                    if i >= 4:
                        row = i + 1
                        B_cell = val[column_index_from_string("B")-1]
                        E_cell = val[column_index_from_string("E")-1]
                        R_cell = val[column_index_from_string("R")-1]
                        W_cell = str(val[column_index_from_string("W")-1]).strip()
                        AB_cell = val[column_index_from_string("AB")-1]
                        if B_cell is None and E_cell is None and R_cell is None and W_cell == "None" and AB_cell is None:
                            if i == 4:
                                sample_data.append(["CheckList文件", f"[変更履歴]", "没有変更履歴"])
                            else:
                                break
                        if B_cell is None or E_cell is None or R_cell is None or W_cell == "None" or AB_cell is None:
                            sample_data.append(["CheckList文件", f"[変更履歴][B{row}-E{row}-R{row}-W{row}-AB{row}]", "单元格数据有[None]值"])
                        if J_date is None or W_cell == "None" or are_dates_equal(W_cell,"%Y-%m-%d %H:%M:%S", J_date,"%Y/%m/%d") == False:
                            sample_data.append(["CheckList文件", f"[変更履歴][W{row}]", "单元格日期数据与[表紙]日期不一致"])
            else:
                sample_data.append(["CheckList文件", "", "未找到[変更履歴]sheet页"])
            check_list = ["I","K","M","O","Q","S","U","W","Y","W","AA","AC","AE"]
            check_no = []
            if sheet_str in CheckList_data:
                tmp_data = CheckList_data[sheet_str]
                for i,val in enumerate(tmp_data):
                    if i > 0:
                        for k in range(len(module_no)):
                            tmp_cell = str(val[column_index_from_string(check_list[k])-1]).strip()
                            if tmp_cell == "None":
                                sample_data.append(["CheckList文件", f"[{sheet_str}][{check_list[k]}{i+1}]", "单元格数据为None"])
                            if i == 2:
                                check_no.append(tmp_cell.replace("No.",""))
                if module_no != check_no:
                    sample_data.append(["CheckList/Module文件", "", "案件号不一致"])
            else:
                sample_data.append(["CheckList文件", "", f"未找到[{sheet_str}]sheet页"])
        except Exception as e:
            print(e)
            QMessageBox.critical(self, "错误", f"21MM检查失败: {e}")
            return

        self.start_btn.ProgressBar(100)
        if sample_data:
            self.table_window.set_data(sample_data)
            self.table_window.set_header(["file name","cell info[sheet+cell]", "Error description"])
            self.table_window.show_table()
            QMessageBox.information(self, "完成", "21MM检查完成,请注意查看具体错误信息 !!!")
        else:
            QMessageBox.information(self, "完成", "21MM检查完成,没有错误信息 !!!")


# 定义第二个页面
class Page_24MM(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("24MM 集约文检查工具")
        self.label.setAlignment(Qt.AlignCenter)  # 方法1：直接设置对齐方式
        self.Jira_path = OpenFileWidget('Jira path:    ')
        self.Module_path = OpenFileWidget('Module path:    ')
        self.start_btn = StartButtonWidget(self.start_exce)
        self.table_window = TableWindow(self)
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.Jira_path)
        layout.addWidget(self.Module_path)
        layout.addWidget(self.start_btn)
        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        layout.addWidget(separator)
        layout.addWidget(self.table_window)
        self.setLayout(layout)

    def clear(self):
        # 清除UI中的输入和显示
        self.Jira_path.clear()
        self.Module_path.clear()
        self.start_btn.clear()
        self.table_window.clear_table()
    
    def start_exce(self):
        try:
            jira_reader = ExcelReader(self.Jira_path.file_name)
            # 读取整个文件的数据
            jira_data = jira_reader.read_all_data()
            # print("整个文件的数据:", jira_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取Jira文件失败: {e}")
            return
        try:
            module_reader = ExcelReader(self.Module_path.file_name)
            # 读取整个文件的数据
            module_data = module_reader.read_all_data()
            # print("整个文件的数据:", module_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取Module文件失败: {e}")
            return

        sample_data = []
        jira_list = []
        jira_dict = {}
        for sheet,jira_info in jira_data.items():
            for r,r_val in enumerate(jira_info):
                jira_num = str(r_val[1]).strip()
                if jira_num == "None":
                    break
                for v,val in enumerate(r_val):
                    str_val = str(val).strip()
                    if r == 0:
                        if str_val == "修正バージョン":
                            jira_list.append(v)
                    else:
                        if v in jira_list:
                            if jira_num in jira_dict:
                                jira_dict[jira_num] = f"{jira_dict[jira_num]},{str_val}"
                            else:
                                jira_dict[jira_num] = str_val
        
        check_list = ["JIRA\nTicket","織り込み内容(日文)"]
        module_columns = {}
        for key,values in module_data.items():
            ver = str(values[0][11]).strip().replace("集約予定Ver：","")
            ok_list = []
            for r,r_val in enumerate(values):
                if str(r_val[1]).strip() == "案件截止":
                    break
                if r == 3:
                    for v, val in enumerate(r_val):
                        str_val = str(val).strip()
                        if str_val == "确认结果":
                            ok_list.append(v)
                        for check in check_list:
                            if str_val == check:
                                module_columns[v] = check
                    if len(module_columns) != len(check_list):
                        QMessageBox.critical(self, "错误", f"Module文件, 第四行特殊数据列[{check_list}]数据不全。")
                        return
                
                if r > 3:
                    for v, val in enumerate(r_val):
                        str_val = str(val).strip()
                        if v in ok_list:
                            if str_val == "NG" or str_val == "None":
                                sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]","单元格数据是[NG/None]"])
                        else:
                            if v in module_columns:
                                if module_columns[v] == "JIRA\nTicket":
                                    if str_val not in jira_dict:
                                        sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]",f"单元格数据[{str_val}]在Jira文件中未找到对应数据"])
                                    else:
                                        if ver not in jira_dict[str_val]:
                                            sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]",f"单元格数据[{str_val}]在Jira文件中修正バージョン数据不是[{ver}]"])
                                if module_columns[v] == "織り込み内容(日文)":
                                    # 定义中文字符的Unicode范围
                                    CHINESE_PATTERN = re.compile(r'[\u4e00-\u9fff]')
                                    JAPANESE_PATTERN = re.compile(r'[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF]')
                                    chinese_char_pattern = re.compile(r'[\u4e00-\u9fff]')
                                    if CHINESE_PATTERN.search(str_val) and not JAPANESE_PATTERN.search(str_val):
                                        sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]",f"单元格数据[{str_val}]中有中文字符"])
                            else:
                                if val is None:
                                    sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]","单元格为数据为[None]"])

        self.start_btn.ProgressBar(100)
        if sample_data:
            self.table_window.set_data(sample_data)
            self.table_window.set_header(["file name","cell info[sheet+cell]", "Error description"])
            self.table_window.show_table()
            QMessageBox.information(self, "完成", "24MM 检查完成,请注意查看具体错误信息 !!!")
        else:
            QMessageBox.information(self, "完成", "24MM 检查完成,没有错误信息 !!!")

        

# 定义第三个页面
class Page_26MM_Step3(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.label = QLabel("26MM_Step3 集约文档暂不使用工具检查 !!!")
        self.label.setAlignment(Qt.AlignCenter)  # 设置标签内容居中
        layout.addWidget(self.label)
        self.setLayout(layout)

# 定义第四个页面
class Page_26MM_CECHAL(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("26MM_CECHAL 集约文检查请使用 24MM 检查工具")
        self.label.setAlignment(Qt.AlignCenter)  # 方法1：直接设置对齐方式
        # self.Jira_path = OpenFileWidget('Jira path:    ')
        # self.Module_path = OpenFileWidget('Module path:    ')
        # self.start_btn = StartButtonWidget(self.start_exce)
        # self.table_window = TableWindow(self)
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        # layout.addWidget(self.Jira_path)
        # layout.addWidget(self.Module_path)
        # layout.addWidget(self.start_btn)
        # # 添加分隔线
        # separator = QFrame()
        # separator.setFrameShape(QFrame.HLine)
        # separator.setFrameShadow(QFrame.Sunken)
        # layout.addWidget(separator)
        # layout.addWidget(self.table_window)
        self.setLayout(layout)

    def clear(self):
        pass
        # 清除UI中的输入和显示
        # self.Jira_path.clear()
        # self.Module_path.clear()
        # self.table_window.clear_table()
    
    def start_exce(self):
        print("***************")

# 定义第五个页面
class Page_Nissan(QWidget):
    def __init__(self):
        super().__init__()
        self.label = QLabel("Nissan-meter 集约文检查工具")
        self.label.setAlignment(Qt.AlignCenter)  # 方法1：直接设置对齐方式
        self.Module_path = OpenFileWidget('Module path:    ')
        self.start_btn = StartButtonWidget(self.start_exce)
        self.table_window = TableWindow(self)
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.Module_path)
        layout.addWidget(self.start_btn)
        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        layout.addWidget(separator)
        layout.addWidget(self.table_window)
        self.setLayout(layout)

    def clear(self):
        # 清除UI中的输入和显示
        self.Module_path.clear()
        self.start_btn.clear()
        self.table_window.clear_table()
    
    def start_exce(self):
        try:
            module_reader = ExcelReader(self.Module_path.file_name)
            # 读取整个文件的数据
            module_data = module_reader.read_all_data()
            # print("整个文件的数据:", module_data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取Module文件失败: {e}")
            return
        
        sample_data = []
        check_list = ["确认结果","release\nbranch"]
        for key,values in module_data.items():
            pass_list = []
            inner_list = []
            module_columns = {}
            if "Popup" in key or "AD" in key or "Ordinary" in key:
                for r,r_val in enumerate(values):
                    if r == 3:
                        for v, val in enumerate(r_val):
                            str_val = str(val).strip()
                            if str_val == "备考":
                                pass_list.append(v)
                            if "inner version" in str_val:
                                inner_list.append(v)
                            for check in check_list:
                                if str_val == check:
                                    module_columns[v] = check
                        if len(module_columns) != len(check_list):
                            QMessageBox.critical(self, "错误", f"Module文件, 第四行特殊数据列[{check_list}]数据不全。")
                            return
                    
                    if r > 3:
                        if r_val[0] is not None:
                            st_flag = False
                            for v, val in enumerate(r_val):
                                if v in pass_list:
                                    continue
                                if v in inner_list:
                                    if str(val).strip() == "●":
                                        st_flag = True
                                else:
                                    if v in module_columns:
                                        if module_columns[v] == "确认结果" and str(val).strip() != "OK":
                                            sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]","单元格数据不是[OK]"])
                                        if module_columns[v] == "release\nbranch" and str(val).strip() != "●":
                                            sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]","单元格数据不是[●]"])
                                    else:
                                        if val is None:
                                            sample_data.append(["Module文件", f"[{key}][{get_column_letter(v+1)}{r+1}]","单元格数据为[None]"])
                            if st_flag == False:
                                sample_data.append(["Module文件", f"[{key}][J{r+1}-R{r+1}]","单元格数据没有[●]"])

        self.start_btn.ProgressBar(100)
        if sample_data:
            self.table_window.set_data(sample_data)
            self.table_window.set_header(["file name","cell info[sheet+cell]", "Error description"])
            self.table_window.show_table()
            QMessageBox.information(self, "完成", "Nissan-meter 检查完成,请注意查看具体错误信息 !!!")
        else:
            QMessageBox.information(self, "完成", "Nissan-meter 检查完成,没有错误信息 !!!")